### Fit baseline model specification

date()
library("purrr")
source("backend_main.r")
sessionInfo()


load("kr_analysis_dispute.rda")
load("kr_analysis_participant.rda")
load("confirm_fit_base.rda")    # Estimates reported in paper
load("startvals_fit_base.rda")  # Starting values used to fit from scratch


## Set to FALSE to estimate from scratch (takes much longer)
CONFIRM_MODE <- TRUE

## Model formulas
f_dispute <- id + war + win_a + win_b_alt ~
  polity_a + majpow_a + log1p(py_alt) + s_cinc + contig |
  polity_b + majpow_b + log1p(py_alt) + s_cinc + contig |
  log(n_states_a) | log(n_states_b)
f_participant <- id + sidea ~
  log(gdp_pwt) + log1p(irst) + log1p(pec) + log1p(tpop) + log1p(upop) +
  log1p(distance) + nuclear | log1p(pct_imports) + polity2

## Fitting process
fit_base <- est_structwar_ac(f_dispute = f_dispute,
                             f_participant = f_participant,
                             data_dispute = data_dispute,
                             data_participant = data_participant,
                             n_halton = 1024,
                             init = if (CONFIRM_MODE) confirm_fit_base else startvals_fit_base,
                             scale = TRUE,
                             reltol = 1e-14,
                             iterlim = 5000,
                             printLevel = 1)

## Confirm that coefficients match
if (CONFIRM_MODE) {
  for (i in seq_along(confirm_fit_base)) {
    stopifnot(all.equal(coef(fit_base[[i]]$fit), confirm_fit_base[[i]]))
  }
}

## Draw dispute indices for bootstrap samples
## Random seeds generated 2022-06-27 by random.org
seeds <- c(100204, 427272, 132513, 176237, 696,
           943821, 612920, 308872, 708857, 792705)
boot_index_base <- vector("list", length(fit_base))
for (i in seq_along(fit_base)) {
  set.seed(seeds[i])
  fit <- fit_base[[i]]
  boot_index_base[[i]] <- foreach (b = 1:100, .combine = "rbind") %do% {
    sample(fit$data_dispute$id,
           size = nrow(fit$data_dispute),
           replace = TRUE)
  }
}

if (!dir.exists("results"))
  dir.create("results")
save(fit_base, file = "results/fit_base.rda")
save(boot_index_base, file = "results/boot_index_base.rda")


date()
